package ws.jdbc.concurrent.driver.sqlserver.tds;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.LinkedList;
import java.util.List;

/**
 * Handles the {@code COLINFO} token reading process.
 *
 * <p>
 * The {@code COLINFO} describes the column information in browse mode
 * <a href="http://go.microsoft.com/fwlink/?LinkId=140931">[MSDN-BROWSE]</a>,
 * {@code sp_cursoropen}, and {@code sp_cursorfetch}.
 * </p>
 *
 * <p>
 * <a href="http://msdn.microsoft.com/en-us/library/dd358065">Reference</a>
 * </p>
 *
 * @author Wilson Santos, 36228 <wilson.santos@ua.pt>
 */
public class ColInfoTokenReader extends TokenReader {

  /**
   * The actual data length, in bytes, of the ColProperty stream.
   * The length does not include token type and length field.
   */
  private short length;
  private List<ColProperty> colPropList;

  /**
   * Create a new reader instance.
   *
   * @param stream data input stream to read the token from.
   */
  public ColInfoTokenReader(ByteBuffer stream) {
    super(stream);
  }

  /**
   * Read one {@code COLINFO} token.
   *
   * @return number of bytes read.
   *
   * @throws IOException if an error occurs while reading from the data input stream.
   */
  @Override
  int read() throws IOException {
    ColProperty colProp;
    colPropList = new LinkedList<ColProperty>();

    // Length
    length = stream.getShort();

    // 1*ColProperty
    colProp = new ColProperty();
    int bytesRead = colProp.read(stream);
    colPropList.add(colProp);

    while ((length - bytesRead) > 0) {
      colProp = new ColProperty();
      bytesRead += colProp.read(stream);
      colPropList.add(colProp);
    }

    return 2 + bytesRead;
  }

  @Override
  public String toString() {
    return "ColInfoTokenReader{"
            + "\n  length=" + length
            + "\n  colPropList=" + colPropList
            + "\n}\n";
  }
}
